var util = require('./utils/util.js');
var api = require('./config/api.js');
const app = getApp();
App({
    onShow() {
        let token = wx.getStorageSync('token');
        if (token) {
            this.getToken(token);
        }else{
            this.authToken();
        }
    },
    getMemberInfo() {
        util.request(api.MemberInfo).then(res=>{
            if(res.code==200){
                if(res.result.nikeName && res.result.phone){
                    wx.setStorageSync('userInfo', res.result)
                }
                this.globalData.cartNum = res.result.shoppingCartCount
                if(this.globalData.cartNum > 0){
                    wx.setTabBarBadge({
                        index: 3,
                        text: this.globalData.cartNum.toString()
                    })
                }
            }
        }).catch(err=>{
            console.log(err)
        })
    },
    async authToken() {
        // let _this = this;
        await util.getTokenFromServer();
        await this.getMemberInfo();

    },
    async getToken(token) {
        let _this = this;
        try{
            const res = await util.request(api.MemberVerify, {token: token}, 'POST');
            if (!res.result || res.code === 401) {
                _this.authToken()
            }else{
                let userInfo = wx.getStorageInfoSync('userInfo');
                if(userInfo && userInfo.nickName && userInfo.phone){
                    return ;
                }
                _this.getMemberInfo();
            }
        }catch(err){
            console.log(err)
        }

    },
    onLaunch() {
        let _this = this;
        // 展示本地存储能力
        const logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)
        wx.getSystemInfo({
            success: res => {
                //导航高度
                _this.globalData.navHeight = res.statusBarHeight + 46;
            },
            fail(err) {
                console.log(err);
            }
        })
        const menu = wx.getMenuButtonBoundingClientRect();
        console.table(menu);
        // 胶囊高度
        _this.globalData.barHeight = menu.top;
        _this.globalData.menuButton = menu;

        // 登录
        // let token = wx.getStorageSync('token');
        // if (token == '') {
        //     _this.authToken()
        // }
    },
    globalData: {
        id_for_category:0,
        userInfo: null,
        navHeight: 0,
        token: '',
        couponList: [],
        memberLeaderObj: {}, //团长的相关信息
        cartNum: 0, //购物车数量
        isCartPage: false,
    }
})
